import config from '@/config'

const _request = function (method, url, data, header, flag = false) {
  if (flag) {
    uni.showLoading({
      title: '加载中',
      mask: true,
    })
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: config.apiBaseUrl + url,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        Authorization: uni.getStorageSync('token') || '',
        ...header,
      },
      success: res => {
        uni.hideLoading()

        if (res.data.code === 0) {
          resolve(res.data)
        } else if ([201, 202, 501].includes(res.data.code)) {
          reject(res.data)
        } else if (res.data.code === -1) {
          uni.showToast({ title: res.data.message, icon: 'none' })
          reject(res.data)
        } else {
          uni.showToast({ title: res.data.message, icon: 'none' })
          reject(res.data)
        }
      },
      fail: err => {
        uni.hideLoading()
        uni.showToast({ title: '服务器开小差啦，稍后再试～', icon: 'none' })
        reject(err)
      },
    })
  })
}

const request = {}

request.get = ({ url, data, flag }) => {
  return _request('GET', url, data, flag)
}

request.post = ({ url, data, flag }) => {
  return _request('POST', url, data, flag)
}

request.put = ({ url, data, flag }) => {
  return _request('PUT', url, data, flag)
}

request.delete = ({ url, data, flag }) => {
  return _request('DELETE', url, data, flag)
}

export default request
